<template>
    <div class="StockChart">
        <div class="echarts">
            <Echarts :option="option" />
        </div>
        <div class="ma" v-if="details.transaction">
            <div class="list">
                <div class="item" :style="{ color: ma5Color }" @click="maClick({ ma: 5, price: transactionLatest.ma5 })">ma5:
                    {{ transactionLatest.ma5 }}</div>
                <div class="item" :style="{ color: ma10Color }" @click="maClick({ ma: 10, price: transactionLatest.ma10 })">
                    ma10: {{ transactionLatest.ma10 }}</div>
                <div class="item" :style="{ color: ma20Color }" @click="maClick({ ma: 20, price: transactionLatest.ma20 })">
                    ma20: {{ transactionLatest.ma20 }}</div>
                <div class="item" :style="{ color: ma30Color }" @click="maClick({ ma: 30, price: transactionLatest.ma30 })">
                    ma30: {{ transactionLatest.ma30 }}</div>
                <div class="item" :style="{ color: ma60Color }" @click="maClick({ ma: 60, price: transactionLatest.ma60 })">
                    ma60: {{ transactionLatest.ma60 }}</div>
                <div class="item" :style="{ color: ma90Color }" @click="maClick({ ma: 90, price: transactionLatest.ma90 })">
                    ma90: {{ transactionLatest.ma90 }}</div>
                <div class="item" :style="{ color: ma120Color }" @click="maClick({ ma: 120, price: transactionLatest.ma120 })">
                    ma120: {{ transactionLatest.ma120 }}</div>
                <div class="item" :style="{ color: ma250Color }" @click="maClick({ ma: 250, price: transactionLatest.ma250 })">
                    ma250: {{ transactionLatest.ma250 }}</div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { reactive, watch, computed, nextTick } from "vue"

import $u from "@/u"
import $color from "@/color"

import Echarts from "@/components/Echarts/Echarts.vue"

const props = defineProps({
    watermark: {
        type: String,
        default: ""
    },
    details: {
        type: Object,
        default: () => ({})
    },
    zoom: {
        type: Boolean,
        default: false
    }
})

const emit = defineEmits(["stockChartMaClick"])

const option = reactive({})

const textColor = "#6a6c78"
const borderColor = "#20232c"
const borderWidth = 1

const ma5Color = "#fff"
const ma10Color = "#cfa968"
const ma20Color = "#9c56b8"
const ma30Color = "#9e1e1f"
const ma60Color = "#c97f58"
const ma90Color = "#5d7fc6"
const ma120Color = "#6bbbdc"
const ma250Color = "#24842d"

const transactionLatest = computed(() => {
    let { transaction } = props.details
    return transaction.at(-1)
})

watch(() => props, async () => {
    await nextTick()
    if (!props.details?.code) return false
    renderChart()
}, { immediate: true, deep: true })


const renderChart = () => {
    let { watermark, details, zoom } = props
    let { transaction = [], calculate: { macd: { macd = [] } }, analysis = {} } = details

    const axisCommon = { axisLine: { show: false }, splitLine: { show: false }, axisTick: { show: false }, axisLabel: { show: false } }

    // 用 markArea 标注背离 和 push k线
    const markAreaDivergence = (() => {
        let result = {
            markArea: {
                silent: true,
                data: []
            }
        }
        let { bottom, top } = analysis.divergence

        if (bottom) {
            let style = {
                label: {
                    position: "inside",
                    formatter: `底背离[${bottom.range.length}]`,
                    fontWeight: "bold",
                    fontSize: 10,
                    color: $color.downColor
                },
                itemStyle: {
                    borderWidth: 0.8,
                    borderType: "dashed",
                    borderColor: $color.downBorderColor,
                    color: $color.downBackgroundColor
                },
            }
            result.markArea.data.push([
                { xAxis: bottom.range.at(0), ...style },
                { xAxis: bottom.range.at(-1), ...style }
            ])
        }
        if (top) {
            let style = {
                label: {
                    position: "inside",
                    formatter: `顶背离[${top.range.length}]`,
                    fontWeight: "bold",
                    fontSize: 10,
                    color: $color.upColor
                },
                itemStyle: {
                    borderWidth: 0.8,
                    borderType: "dashed",
                    borderColor: $color.upBorderColor,
                    color: $color.upBackgroundColor
                },
            }
            result.markArea.data.push([
                { xAxis: top.range.at(0), ...style },
                { xAxis: top.range.at(-1), ...style }
            ])
        }

        if (transaction.at(-1).isPush) {
            let transactionLength = transaction.length
            let style = {
                label: {
                    position: "inside",
                    formatter: "",
                    fontWeight: "bold",
                    fontSize: 10,
                    color: "#fff"
                },
                itemStyle: {
                    borderWidth: 0.8,
                    borderType: "dashed",
                    borderColor: "rgba(255, 255, 255, 0.1)",
                    color: "rgba(255, 255, 255, 0.06)"
                },
            }
            result.markArea.data.push([
                { xAxis: transactionLength - 2, ...style },
                { xAxis: transactionLength - 1, ...style }
            ])
        }

        return result
    })()


    // 用 markLine 标注背离
    const markLineDivergence = (() => {
        let result = {
            markLine: {
                silent: true,
                data: [],
                symbolSize: 8
            }
        }
        let { bottom, top } = analysis.divergence
        if (bottom) {
            let style = {
                lineStyle: {
                    type: 'dashed',
                    color: $color.downColor
                }
            }
            result.markLine.data.push([
                { coord: [bottom.range.at(0), transaction.at(bottom.range.at(0)).low], ...style }, // 第一根柱子的低点坐标（x轴索引0，y轴值10）
                { coord: [bottom.range.at(-1), transaction.at(bottom.range.at(-1)).low], ...style } // 最后一根柱子的低点坐标（x轴索引3，y轴值5）
            ])
        }
        if (top) {
            let style = {
                lineStyle: {
                    type: 'dashed',
                    color: $color.upColor
                }
            }
            result.markLine.data.push([
                { coord: [top.range.at(0), transaction.at(top.range.at(0)).high], ...style }, // 第一根柱子的低点坐标（x轴索引0，y轴值10）
                { coord: [top.range.at(-1), transaction.at(top.range.at(-1)).high], ...style } // 最后一根柱子的低点坐标（x轴索引3，y轴值5）
            ])
        }
        return result
    })()


    const dataZoom = zoom ? [{
        type: 'inside',
        xAxisIndex: "all",
        start: 99,
        end: 100,
        minSpan: 25
    }] : [{
        type: 'inside',
        start: 0,
        end: 100,
        minSpan: 25
    }]

    let timeData = [] // 日期 ["2012-02-04"]
    let transactionData = [] // K线 [open, close, low, high]
    let macdData = [] // macd [-3, -2, -1, 1]
    // let kdData = { k: [], d: [] } // kd [-3, -2, -1, 1]

    let ma5Data = [] // 5均线
    let ma10Data = [] // 10均线
    let ma20Data = [] // 20均线
    let ma30Data = [] // 30均线
    let ma60Data = [] // 60均线
    let ma90Data = [] // 90均线
    let ma120Data = [] // 120均线
    let ma250Data = [] // 250均线

    let volumeData = [] // 成交量 [257841651]
    let volume5Data = [] // 5成交量
    let volume10Data = [] // 10成交量

    transaction.forEach(({ time, open, close, low, high, volume, ma5, ma10, ma20, ma30, ma60, ma90, ma120, ma250, volume5, volume10 }, index) => {
        let macdItem = macd[index]

        timeData.push(index)
        // timeData.push(time)
        transactionData.push([open, close, low, high])
        macdData.push({ value: macdItem, itemStyle: { color: macdItem > 0 ? $color.upColor : $color.downColor } })

        // kdData.k.push(k[index])
        // kdData.d.push(d[index])

        ma5Data.push(ma5)
        ma10Data.push(ma10)
        ma20Data.push(ma20)
        ma30Data.push(ma30)
        ma60Data.push(ma60)
        ma90Data.push(ma90)
        ma120Data.push(ma120)
        ma250Data.push(ma250)

        volumeData.push({ value: volume, itemStyle: { color: open < close ? $color.upColor : $color.downColor } })
        volume5Data.push(volume5)
        volume10Data.push(volume10)
    })

    Object.assign(option, {
        color: [ma5Color, ma10Color, ma20Color, ma30Color, ma60Color, ma90Color, ma120Color, ma250Color],
        animation: false,
        dataZoom,
        tooltip: {
            trigger: "axis",
            triggerOn: "mousemove",
            axisPointer: {
                type: "cross",
                snap: false,
                axis: "y",
                label: {
                    backgroundColor: "#589dfc",
                    formatter(params) {
                        let { axisDimension, value } = params
                        if (axisDimension == "x") return transaction[value]?.time
                        return value.toFixed(2)
                    }
                }
            },
            formatter(params) {
                return ""
            },
            backgroundColor: "rgba(22, 25, 34, 0.8)",
            borderWidth: 0,
            textStyle: {
                color: textColor,
            }
        },
        // 定义四个grid区域，分别放置四个子图
        grid: [
            { top: '0%', left: 1, right: 1, height: '88%' }, // 蜡烛图
            { top: '88%', left: 0, right: 0, height: '12%' }  // 折线图
        ],
        xAxis: [
            { type: 'category', data: timeData, gridIndex: 0, ...axisCommon },
            { type: 'category', data: timeData, gridIndex: 1, ...axisCommon }
        ],
        yAxis: [
            { type: 'value', gridIndex: 0, scale: true, ...axisCommon, splitNumber: 5, splitLine: { lineStyle: { width: 0.8, color: borderColor } }, axisLabel: { inside: true, fontSize: 9, color: textColor } },
            { type: 'value', gridIndex: 1, ...axisCommon }
        ],
        series: [
            // 蜡烛图系列
            { name: 'serie', type: 'candlestick', xAxisIndex: 0, yAxisIndex: 0, data: transactionData, ...markAreaDivergence, ...markLineDivergence, itemStyle: { normal: { color: $color.upColor, color0: $color.downColor, borderColor: $color.upColor, borderColor0: $color.downColor } } },
            { name: 'ma5', type: 'line', xAxisIndex: 0, yAxisIndex: 0, data: ma5Data, silent: true, lineStyle: { width: borderWidth }, showSymbol: false },
            { name: 'ma10', type: 'line', xAxisIndex: 0, yAxisIndex: 0, data: ma10Data, silent: true, lineStyle: { width: borderWidth }, showSymbol: false },
            { name: 'ma20', type: 'line', xAxisIndex: 0, yAxisIndex: 0, data: ma20Data, silent: true, lineStyle: { width: borderWidth }, showSymbol: false },
            { name: 'ma30', type: 'line', xAxisIndex: 0, yAxisIndex: 0, data: ma30Data, silent: true, lineStyle: { width: borderWidth }, showSymbol: false },
            { name: 'ma60', type: 'line', xAxisIndex: 0, yAxisIndex: 0, data: ma60Data, silent: true, lineStyle: { width: borderWidth }, showSymbol: false },
            { name: 'ma90', type: 'line', xAxisIndex: 0, yAxisIndex: 0, data: ma90Data, silent: true, lineStyle: { width: borderWidth }, showSymbol: false },
            { name: 'ma120', type: 'line', xAxisIndex: 0, yAxisIndex: 0, data: ma120Data, silent: true, lineStyle: { width: borderWidth }, showSymbol: false },
            { name: 'ma250', type: 'line', xAxisIndex: 0, yAxisIndex: 0, data: ma250Data, silent: true, lineStyle: { width: borderWidth }, showSymbol: false },

            // 状图系列
            { name: 'volume', type: 'bar', xAxisIndex: 1, yAxisIndex: 1, data: volumeData, silent: true },
            { name: 'volume5', type: 'line', xAxisIndex: 1, yAxisIndex: 1, data: volume5Data, silent: true, lineStyle: { width: borderWidth, color: ma5Color }, showSymbol: false },
            { name: 'volume10', type: 'line', xAxisIndex: 1, yAxisIndex: 1, data: volume10Data, silent: true, lineStyle: { width: borderWidth, color: ma10Color }, showSymbol: false },
        ],
        graphic: {
            elements: [
                {
                    type: 'text',
                    left: 'center', // 水印位置
                    top: 'center', // 水印位置
                    z: -10, // 设置z值，确保水印位于图表内容之下
                    style: {
                        text: `${watermark}`, // 水印文字
                        fontWeight: "bold",
                        fontSize: 130,
                        fill: borderColor // 文字颜色与透明度
                    }
                }
            ]
        }

    })
}

const maClick = ({ ma, price }) => {
    emit("stockChartMaClick", { ma, price })
}


const dataZoom = ({ zoom }) => {
    chart.dispatchAction(
        zoom ? {
            type: "dataZoom",
            start: 90,
            end: 100
        } : {
            type: "dataZoom",
            start: 0,
            end: 100
        })
}

defineExpose({
    dataZoom
})

</script>


<style lang="scss" scoped>
.StockChart {
    height: 100%;

    >.echarts {
        height: 100%;
    }

    >.ma {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;

        &::-webkit-scrollbar {
            display: none;
        }

        >.list {
            white-space: nowrap;

            >.item {
                display: inline-block;
                padding: 10upx;
                font-size: 24upx;
            }
        }
    }

}
</style>